﻿$(document).on('pageinit', '#countylist', function (e) {
    if (e.handled != true) {
        // Get Query String
        //var query = $(this).data("url").split("?")[1];;
        //query = query.replace("type=", "");
        //alert("query: " + query);

        // Get Type of Location from Local Storage
        var locationType = GetQueryString("LocationType");

        // Load page header and footer
        $("#locationHeader").load('shared/header.html', function () {
            $(this).trigger('create');
        });
        $("#locationFooter").load('shared/footer.html', function () {
            $(this).trigger('create');
        });

        $('#nearmesearch').click(function () {
            if (navigator.geolocation) {

                // Confirm Use of GPS
                 navigator.notification.confirm(
                    stringConstants.gpsUsageMessage, // message
                     onConfirm,                      // callback to invoke with index of button pressed
                    'Retrieve Location',             // title
                    ['Yes', 'No']                    // buttonLabels
                );

            }
        });







        //$("#countyListSearchDiv").load('shared/search.html', function () {
        //    $(this).trigger('create');
        //});

        // Set Page Title and variables
        var pageTitle = "";
        var locationCountType = null;
        var locationCountTypeBackupURL = null;
        var locationGPS = null;
        switch (locationType) {
            case "DL":
                pageTitle = "Drivers License Locations";
                locationCountType = "LocationCountDL";
                locationCountTypeBackupURL = "api/location/1/count";
                locationGPS = "1";
                break;
            case "TR":
                pageTitle = "County Treasurer Locations";
                locationCountType = "LocationCountTR";
                locationCountTypeBackupURL = "api/location/2/count";
                locationGPS = "2";
                break;
            default:
                pageTitle = "Locations Near Me";
                break;
        }
        $('#locationPageTitle').text(pageTitle);


        // Page Events
        // Show near me search if GPS enabled
        if (GetQueryString("GPS") != 'true') {
            //$('#nearmesearch').closest('.ui-btn').hide();
            $('#nearmesearch').button('disable');
        }
        //if (navigator.geolocation) {
        //}
         

        // Update location count data for counties
        $.when(GetCachedItem(locationCountType, serviceURL + locationCountTypeBackupURL)).done(function (a1) {
            // the code here will be executed when all four ajax requests resolve.
            // a1, a2, a3 and a4 are lists of length 3 containing the response text,
            // status, and jqXHR object for each of the four ajax calls respectively.
            $.each(a1, function (key, value) {
                //if (value.Count != 0) {
                $('#' + value.County.toLowerCase() + "locations").text(value.Count);
                //$('#countyList').find("span[id='" + value.County.toLowerCase() + "locations']").text(value.Count);
                //}
                //else {
                   // $('#countyList').find("span[id='" + value.County.toLowerCase() + "locations']").hide();
                //}
                
            });

            // Remove any counties that have a 0 count after counts are loaded
            $("#countyList li").each(function (index) {
                if ($(this).find('span').text() == 0) {
                    $(this).hide();
                }
            });



            $('#distanceslider').focus();



        });


        // Near me search button handlers
        $('#addresssearch').click(function () {
            // Make sure search text isn't null or has at least 5 characters
            if ($('#nearmeaddress').val() && $('#nearmeaddress').val().length > 4) {

                // Encode url string
                var addressPart = encodeURIComponent($('#nearmeaddress').val());
                $.getJSON('https://maps.googleapis.com/maps/api/geocode/json?address=' + addressPart, function (data) {
                    var lat = null;
                    var lng = null;
                    for (i = 0; i < data.results.length; i++) {
                        lat = data.results[i].geometry.location.lat;
                        lng = data.results[i].geometry.location.lng;
                    }

                    alert("lat: " + lat);
                    alert("lon: " + lng);

                    DistanceSearch(lat + ',' + lng, $('#distanceslider').val());
                });
            }
            else {
                $('#officelist2').empty();
                $('#officelist2').append("<li><h6>No Results Found</h6></li>").listview('refresh');    //.listview('refresh');
            }
        });


        function DistanceSearch(pos, distance) {
           // $('#distanceList').show();
            $('#officelist2').empty();
            $.getJSON(serviceURL + 'api/location/' + pos + '/' + distance + "/" + locationGPS + '/nearme', function (data) {
                // If no data returned, write message
                if (data.length == 0) {
                    $('#officelist2').append("<li><h6>No Results Found</h6></li>").listview('refresh');    //.listview('refresh');
                }

                // Write out each row
                $.each(data, function (key, value) {
                    $('#officelist2').append("<li><a href='office.html' onclick='SaveQueryString(\"countyidparm\", \"" + value.locationID + "\")'><img src=\"" + value.streetViewURL + "\"' height='80px' width='80px' /><h6 class='wrap'>" + value.locationName + '      </h6><p>Distance: ' + value.distance + ' Miles</p></a></li>').listview('refresh'); //.listview('refresh');
                    //$('#officelist2').append("<li><a href='restaurant.html'><h2>Docking State office</h2></a></li>").listview('refresh'); //.listview('refresh');
                });
            });
            //$('#officelist2').listview('refresh');
        };


        // process the confirmation dialog result
        function onConfirm(buttonIndex) {
            if (buttonIndex == 1) {
                var positionData;
                navigator.geolocation.getCurrentPosition(function (pos) {
                    positionData = pos.coords.latitude + ',' + pos.coords.longitude;
                    DistanceSearch(positionData, $('#distanceslider').val());
                    $('#officelist2').focus();
                });
            }
        };

        e.handled = true;
    }
});